package speakershareclient;

import java.io.OutputStream;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.*;

public class Client implements Runnable {

    private TargetDataLine targetDataLine;
    private Socket sock;
    private OutputStream out;
    private Mixer.Info mixerInfo;
    private Mixer mixer;
    private static Mixer.Info[] mixerInfos;
    DataLine.Info dli;

    public void run() {
        mixerInfo = mixerInfos[2];
        mixer = AudioSystem.getMixer(mixerInfo);

        // Open target data line
        dli = new DataLine.Info(TargetDataLine.class, Settings.audioFormat);
        
        try {
            targetDataLine = (TargetDataLine) mixer.getLine(dli);
            targetDataLine.open(Settings.audioFormat);
            targetDataLine.start();

            // Connect to server
            sock = new Socket("127.0.0.1", Settings.PORT);
            System.out.println("Connected.");
            out = sock.getOutputStream();

            byte[] chunk = new byte[Settings.CHUNK_SIZE];
            while (true) {
                    int numBytesRead = targetDataLine.read(chunk, 0, chunk.length);
                    out.write(chunk, 0, numBytesRead);
                    System.out.println("Written.");
            }
        } catch (Exception ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) {
        // List available mixers
        mixerInfos = AudioSystem.getMixerInfo();
        for(Mixer.Info mi : mixerInfos){
            System.out.println(mi);
        }

        Thread t = new Thread(new Client());
        t.start();
    }
}
